package com.zyk.scaffold.core.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

/**
 * redis 计数限制组件
 */
@Slf4j
public class CountRedisLimitComponent {

    private static final String REDIS_LIMIT_KEY = "limit:count:";


    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> tryScript = new DefaultRedisScript<>();
    private DefaultRedisScript<Long> incrbyScript = new DefaultRedisScript<>();
    {

        incrbyScript.setScriptSource(new ResourceScriptSource(
                new ClassPathResource("META-INF/scripts/count-number-limiter-incrby.lua")));
        incrbyScript.setResultType(Long.class);
        tryScript.setScriptSource(new ResourceScriptSource(
                new ClassPathResource("META-INF/scripts/count-number-limiter-try.lua")));
        tryScript.setResultType(Long.class);
    }

    public CountRedisLimitComponent(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 计数累计
     * @param key
     * @param seconds
     */
    public void incrby(String key, int seconds) {
        List<String> keys = new ArrayList<>();
        keys.add(REDIS_LIMIT_KEY + key);
        Long count = stringRedisTemplate.execute(incrbyScript, keys, String.valueOf(seconds));
        log.info("CountRedisLoginComponent:" + key + "-lock-count:" + count);
    }

    /**
     * 检测 是否 value > limitCount
     * @param key
     * @param limitCount
     * @return
     */
    public boolean check(String key, int limitCount) {
        List<String> keys = new ArrayList<>();
        keys.add(REDIS_LIMIT_KEY + key);
        Long count = stringRedisTemplate.execute(tryScript, keys, String.valueOf(limitCount));
        if (count != 0) {
            return true;
        } else {
            return false;
        }
    }
}
